//
//  GMTorrentListModel.m
//  gentleman
//
//  Created by 范月成 on 2017/12/14.
//  Copyright © 2017年 fancy. All rights reserved.
//

#import "GMTorrentListModel.h"
#import "VendorHeader.h"
#import "GMUIHelper.h"

@interface GMTorrentListModel()

@property (nonatomic, strong, readwrite) NSMutableArray <GMTorrent *>*listDatas;

@end

@implementation GMTorrentListModel

- (void)getTorrentListWithGid:(NSInteger)gid
                        token:(NSString *)token
                    completed:(getTorrentsCompleted)completed {
    NSString *api = [NSString stringWithFormat:@"gallerytorrents.php?gid=%ld&t=%@", gid, token];
    [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
        request.api = api;
        request.httpMethod = kXMHTTPMethodGET;
        request.responseSerializerType = kXMResponseSerializerRAW;
    } onSuccess:^(id  _Nullable responseObject) {
        TFHpple *parser = [[TFHpple alloc] initWithHTMLData:responseObject];
        NSArray *torrentDatas = [parser searchWithXPathQuery:@"//form [@method='post']//table"];
        if (!torrentDatas.count) {
            !completed?:completed([NSError errorWithDomain:@"no torrents" code:444 userInfo:nil], nil);
            return;
        }
        NSMutableArray *torrents = [NSMutableArray array];
        for (TFHppleElement *subElement in torrentDatas) {
            GMTorrent *torrent = [[GMTorrent alloc] init];
            torrent.posted = [[subElement searchWithXPathQuery:@"//td"].firstObject text];
            torrent.size = [[subElement searchWithXPathQuery:@"//td"][1] text];
            torrent.seeds = [[subElement searchWithXPathQuery:@"//td"][3] text];
            torrent.peers = [[subElement searchWithXPathQuery:@"//td"][4] text];
            torrent.downloads = [[subElement searchWithXPathQuery:@"//td"][5] text];
            torrent.uploader = [[subElement searchWithXPathQuery:@"//td"][6] text];
            torrent.name = [[subElement searchWithXPathQuery:@"//td//a"].firstObject text];
            NSString *url = [subElement searchWithXPathQuery:@"//td//a"].firstObject[@"href"];
            torrent.magnet = [NSString stringWithFormat:@"magnet:?xt=urn:btih:%@",[[url componentsSeparatedByString:@"/"].lastObject stringByDeletingPathExtension]];
            [torrents addObject:torrent];
        }
        self.listDatas = torrents;
        !completed?:completed(nil, torrents);
    } onFailure:^(NSError * _Nullable error) {
        !completed?:completed(error, nil);
    }];
}

#pragma mark - TableView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    YYLabel *header = [GMUIHelper generalTitleLabel];
    header.frame = CGRectMake(0, 0, kScreenWidth, 30);
    header.text = @"种子信息";
    header.textContainerInset = UIEdgeInsetsMake(0, 15, 0, 0);
    return header;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listDatas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString * const identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    
    [self configData:cell indexPath:indexPath];
    
    return cell;
}

- (void)configData:(UITableViewCell *)cell
         indexPath:(NSIndexPath *)indexPath {
    GMTorrent *torrent = self.listDatas[indexPath.section];
    NSString *title = nil;
    NSString *detail = nil;
    switch (indexPath.row) {
        case 0:
            title = @"Name";
            detail = torrent.name;
            break;
        case 1:
            title = @"Uploader";
            detail = torrent.uploader;
            break;
        case 2:
            title = @"Posted";
            detail = torrent.posted;
            break;
        case 3:
            title = @"Size";
            detail = torrent.size;
            break;
        case 4:
            title = @"Seeds";
            detail = torrent.seeds;
            break;
        case 5:
            title = @"Peers";
            detail = torrent.peers;
            break;
        case 6:
            title = @"Downloads";
            detail = torrent.downloads;
            break;
        case 7:
            title = @"Magnet";
            detail = torrent.magnet;
            break;
            
        default:
            break;
    }
    
    cell.textLabel.text = title;
    cell.detailTextLabel.textColor = [UIColor themeBlack];
    cell.detailTextLabel.text = detail;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
 
    GMTorrent *torrent = self.listDatas[indexPath.section];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = torrent.magnet;
    
    [GMUIHelper alertWithTitle:@"已复制" message:torrent.magnet];
}


@end
